package com.sdlh.demo.concurrent;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

@Slf4j
public class InterruptDemo {

    public static void main() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            int num = 0;
            int count = 0;
            int max = Integer.MAX_VALUE / 2;
            log.info("max={}", max);
            //打印最大整数一半的范围内79的倍数
            while (num <= max && !Thread.currentThread().isInterrupted()) {
                if (num % 79 == 0) {
                    if (++count == 8) {
                        try {
                            count = 0;
                            log.info("每找到8个79的倍数就阻塞一段时间，当前num={}", num);
                            //当前线程中断只会修改线程中断状态，且该方法不会抛出任何异常，不会清除线程中断状态
//                            LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100));
                            //当前线程中断会修改线程中断状态，且该方法会抛出中断异常，会清除线程中断状态
                            Thread.sleep(100);
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                            log.info("当前interrupt标志位为{}", Thread.currentThread().isInterrupted());
                            Thread.currentThread().interrupt();
                        }
                        log.info("当前interrupt标志位为{}", Thread.currentThread().isInterrupted());
                    }
                }
                ++num;
            }
            log.info("num={}, count={}", num, count);
            log.info("线程t1退出");
            boolean interrupted = Thread.interrupted();
            log.info("interrupted={}, 当前interrupt标志位为{}", interrupted, Thread.currentThread().isInterrupted());

        });
        //启动线程
        t1.start();
        //增加子线程处于运行状态的可能性
        Thread.sleep(300);
        //尝试中断子线程
        t1.interrupt();
    }
}
